<html>
<head>
  <title>aiohttp（搭建服务器）</title>
  <basefont face="微软雅黑" size="2" />
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="exporter-version" content="Evernote Windows/307027 (zh-CN, DDL); Windows/6.1.0 (Win32);"/>
  <style>
    body, td {
      font-family: 微软雅黑;
      font-size: 10pt;
    }
  </style>
</head>
<body>
<a name="615"/>
<h1>aiohttp（搭建服务器）</h1>

<div>
<span><div><div style="text-align: center;"><font style="color: rgb(28, 51, 135); font-size: 24pt;"><b>server</b></font></div><div><font style="font-size: 18pt; color: rgb(28, 51, 135);">一个简单aiohttp服务器模型</font></div><div style="box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, &quot;Courier New&quot;, monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial;-en-codeblock:true;"><div>from aiohttp import web</div><div><br/></div><div>async def hello(request):</div><div><span>    return web.Response(text=&quot;Hello, world&quot;)</span><br/></div><div><span><br/></span></div><div><span>app = web.Application()</span></div><div><span>app.router.add_get('/', hello)</span></div><div><span>web.run_app(app)</span></div></div><div><br/></div><div><br/></div><div><br/></div><div><span style="font-size: 12px;">添加两个方法，和middleware来实现一个稍微复杂一点的例子来分析：</span></div><br/></div><div style="box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, &quot;Courier New&quot;, monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial;-en-codeblock:true;"><div>import asyncio  </div><div>from aiohttp import web  </div><div>  </div><div>#通过localhost:8080访问  </div><div>async def index(request):  </div><div>    resp = web.Response(body=b'&lt;h1&gt;Index&lt;/h1&gt;')  </div><div>    # 如果不添加content_type，某些严谨的浏览器会把网页当成文件下载，而不是直接显示  </div><div>    resp.content_type = 'text/html;charset=utf-8'  </div><div>    return resp  </div><div>  </div><div>#通过localhost:8080/hello/输入一个字符串 访问  </div><div>async def hello(request):  </div><div>    text = '&lt;h1&gt;hello,%s&lt;/h1&gt;' % request.match_info['name']  </div><div>    resp = web.Response(body=text.encode('utf-8'))  </div><div>    #如果不添加content_type，某些严谨的浏览器会把网页当成文件下载，而不是直接显示  </div><div>    resp.content_type = 'text/html;charset=utf-8'  </div><div>    return resp  </div><div>  </div><div>async def init(loop):  </div><div>    app = web.Application(middlewares={  </div><div>        logger1_factory, logger2_factory  </div><div>    })  </div><div>    app.router.add_route('GET','/',index)  </div><div>    app.router.add_route('GET','/hello/{name}',hello)  </div><div>    server = await loop.create_server(app.make_handler(),'localhost',8080)  </div><div>    print('accepting request.....')  </div><div>    return server  </div><div>  </div><div>  </div><div>async def logger1_factory(app,handler):  </div><div>    async def logger1_handler(request):  </div><div>  </div><div>        print('i am logger1')  </div><div>        return await handler(request)  </div><div>    return logger1_handler  </div><div>  </div><div>  </div><div>async def logger2_factory(app,handler):  </div><div>    async def logger2_handler(request):  </div><div>          </div><div>        print('i am logger2')  </div><div>        return await handler(request)  </div><div>    return logger2_handler  </div><div>  </div><div>  </div><div>loop = asyncio.get_event_loop()  </div><div>loop.run_until_complete(init(loop))  </div><div>loop.run_forever()  </div></div><div><div><br/></div><div><ul><li><span style="font-size: 12px;">app.router是一个UrlDispatcher对象，它有一个add_route方法</span></li></ul></div><div><img src="aiohttp（搭建服务器）_files/Image.png" type="image/png" data-filename="Image.png" width="481"/></div><div><ul><li><span style="font-size: 12px;">我们在浏览器中输入 localhost:8080  浏览器会向服务器发送一个请求，method = 'GET'  path = '/'</span></li><li><span style="font-size: 12px;"><br/></span></li></ul></div><div><br/></div><div><br/></div><div><br/></div><div>编写一个HTTP服务器，分别处理以下URL：</div><ul><li>/ - 首页返回b'&lt;h1&gt;Index&lt;/h1&gt;'；</li><li>/hello/{name} - 根据URL参数返回文本hello, %s!。</li></ul><div>代码如下：</div><div style="box-sizing: border-box; padding: 8px; font-size: 12px; border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902);"><div><span style="background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 12px;">import asyncio</span></div><div><br/></div><div><span style="background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 12px;">from aiohttp import web</span></div><div><br/></div><div><span style="background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 12px;">async def index(request):</span></div><div><span style="background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 12px;">    await asyncio.sleep(0.5)</span></div><div><span style="background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; font-size: 12px;">    return web.Response(body=b'&lt;h1&gt;Index&lt;/h1&gt;')</span></div><div><br/></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">async def hello(request):</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">       await asyncio.sleep(0.5)</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">       text = '&lt;h1&gt;hello, %s!&lt;/h1&gt;' % request.match_info['name']</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;"><span>    <span>  </span></span> return web.Response(body=text.encode('utf-8'))</span></div><div><br style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"/></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">async def init(loop):</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;"><span>    <span>    </span></span>app = web.Application(loop=loop)</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;"><span>    <span>    </span></span>app.router.add_route('GET', '/', index)</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;"><span>    <span>    </span></span>app.router.add_route('GET', '/hello/{name}', hello)</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;"><span>    <span>    </span></span>srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;"><span>    <span>    </span></span>print('Server started at</span> <a href="http://127.0.0.1:8000...'/" style="font-size: 9pt; background-color: rgb(251, 250, 248); font-family: Monaco; color: rgb(51, 51, 51);">http://127.0.0.1:8000...'</a><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">;)</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;"><span>    <span>    </span></span>return srv</span></div><div><br style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"/></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">loop = asyncio.get_event_loop()</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">loop.run_until_complete(init(loop))</span></div><div><span style="font-size: 9pt; background-color: rgb(251, 250, 248); color: rgb(51, 51, 51); font-family: Monaco;">loop.run_forever()</span></div></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div style="text-align: center;"><font style="font-size: 24pt; color: rgb(28, 51, 135);"><b>Client</b></font></div><div><br/></div><div>client example:</div><div style="box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, &quot;Courier New&quot;, monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial;-en-codeblock:true;"><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);">import aiohttpimport asyncioimport async_timeout</span></div><div><br style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"/></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);">async def fetch(session, url):</span></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"><span>    </span>with async_timeout.timeout(10):</span></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"><span>    <span>    </span></span>async with session.get(url) as response:</span></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"><span>    <span>    <span>    </span></span></span>return await response.text()</span></div><div><br style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"/></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);">async def main():</span></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"><span>    </span>async with aiohttp.ClientSession() as session:</span></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"><span>    <span>    </span></span>html = await fetch(session, '</span><a href="http://python.org'/" style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);">http://python.org'</a><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);">;)</span></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"><span>    <span>    </span></span>print(html)</span></div><div><br style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);"/></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);">loop = asyncio.get_event_loop()</span></div><div><span style="font-family: Monaco; font-size: 9pt; color: rgb(51, 51, 51);">loop.run_until_complete(main())</span></div></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><div><br/></div><br/></div><div><br/></div></span>
</div></body></html> 